package cn.edu.scau.cmi.lishuoxin.interProgramming.experiment2;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class SomeSingle {

    private SomeSingle() {}
    // 存储创建的实例
    private static Map<Integer, SomeSingle> map = new HashMap<>(10);
    // 计数器从1开始
    private volatile static int num = 1;
    // 控制最多有三个实例
    private static final int MAX_NUM = 10;
    final static ReentrantLock lock = new ReentrantLock();

    public static SomeSingle getInstance() {
        lock.lock();
        try {
            // 从缓存中取出实例
            SomeSingle instance  = map.get(num);
            if (instance == null) {
                instance = new SomeSingle();
                // 计数器作为map的key
                map.put(num, instance);
            }
            // 计数器+1
            num++;
            if (num > MAX_NUM) {
                // 重置计数器
                num = 1;
            }
            return instance;
        } finally {
            lock.unlock();
        }
    }
}